#include "LocalServerManage.h"

#include <QLocalServer>

LocalServerManage::LocalServerManage(const int &handleMaxThreadCount, QObject * parent) :
AbstractManage(handleMaxThreadCount, parent)
{ 

}

LocalServerManage::~LocalServerManage()
{
	if (this->isRunning())
	{
		this->close();
	}
}

bool LocalServerManage::listen(const QString &name)
{
	listenName_ = name;

	return this->begin();
}

bool LocalServerManage::isRunning()
{
	return !localServer_.isNull();
}

bool LocalServerManage::onStart()
{
	mutex_.lock();

	localServer_ = new QLocalServer;

	mutex_.unlock();

	QObject::connect(localServer_.data(), &QLocalServer::newConnection, [this]()
	{
		this->newSession(new Session(this->localServer_->nextPendingConnection()));
	});

	if (!localServer_->listen(listenName_))
	{
		mutex_.lock();

		delete localServer_.data();
		localServer_.clear();

		mutex_.unlock();

		return false;
	}

	return true;
}

void LocalServerManage::onFinish()
{
	this->mutex_.lock();

	localServer_->close();
	delete localServer_.data();
	localServer_.clear();

	this->mutex_.unlock();
}
